package com.cangxuan.app.ui.collection;


import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.os.Bundle;
import android.os.Handler;
import android.view.*;
import android.widget.*;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cangxuan.app.R;
import com.cangxuan.app.entity.*;
import com.cangxuan.app.ui.BaseActivity;
import com.cangxuan.app.ui.fragment.CollectionDetailBottomFragment;
import com.cangxuan.app.ui.fragment.CollectionDetailFragment;
import com.cangxuan.app.ui.fragment.CollectionDetailListBottomFragment;
import com.cangxuan.app.ui.fragment.CollectionInfoFragment;
import com.cangxuan.app.ui.user.MyCollectionActivity;
import com.cangxuan.app.ui.user.OrderformActivity;
import com.cangxuan.app.utils.*;

import java.io.File;
import java.net.HttpURLConnection;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Author: 陈青石
 * Activity: 藏品详情页面
 * Layout: activity_collectiondetail
 */
public class CollectionDetailActivity extends BaseActivity {

    public static List<Registration> registrations = new ArrayList<>();

    Button collectionDetail;
    Button collectionInfo;
    FragmentManager fragmentManager;
    CollectionDetailFragment collectionDetailFragment;
    CollectionInfoFragment collectionInfoFragment;
    static int index;
    public static int id;

    TextView collectionName;
    TextView mintage;
    TextView circulation;
    TextView price;
    ImageView collectionImg;
    Handler handler = new Handler();

    public static Goods goodsDetail;

    LinearLayout detailLoading;
    LinearLayout collectionMid;
    LinearLayout likeLoading;
    LinearLayout bottomView;
    LinearLayout bottomLoad;

    FrameLayout collectionFragment;

    public static int comeFrom;
    Map<String, String> header;
    ImageView imgLike;
    boolean like;
    int width;
    public static int isShow;
    User user;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_collectiondetail);
        fragmentManager = getSupportFragmentManager();
        setTitle("藏品名称");

        user = UserUtils.getUser(getApplicationContext());
        CollectionDetailListBottomFragment.isOpen = 0;
        Display display = getWindowManager().getDefaultDisplay();
        Point point = new Point();
        display.getSize(point);
        width = point.x;

        CollectionDetailBottomFragment.checkCount = 0;
        CollectionDetailBottomFragment.position = 0;
        index = 0;
        header = new HashMap<>();
        header.put("Authorization", DeviceUtils.getDeviceID());

        Intent intent = getIntent();
        id = intent.getIntExtra("goodsId", 0);

        isShow = intent.getIntExtra("isShow", 1);

        boolean isHome = intent.getBooleanExtra("isHome", true);

        comeFrom = isHome ? 0 : 1;

        CollectionDetailBottomFragment.setFragmentVisible();
        CollectionDetailBottomFragment.setCountAndPrice(new ArrayList<>());

        collectionName = findViewById(R.id.collection_name);
        mintage = findViewById(R.id.collection_mintage);
        circulation = findViewById(R.id.collection_circulation);
        price = findViewById(R.id.collection_price);
        detailLoading = findViewById(R.id.detail_loading);
        collectionFragment = findViewById(R.id.collection_fragment);
        collectionImg = findViewById(R.id.collection_img);
        imgLike = findViewById(R.id.img_like);
        collectionDetail = findViewById(R.id.collection_detail);
        collectionInfo = findViewById(R.id.collection_info);
        collectionMid = findViewById(R.id.collection_mid);
        likeLoading = findViewById(R.id.like_loading);
        bottomView = findViewById(R.id.bottom_view);
        bottomLoad = findViewById(R.id.bottom_load);

        collectionDetail.setOnClickListener(view -> {
            replaceFragment(0);
        });

        collectionInfo.setOnClickListener(view -> {
            replaceFragment(1);
        });

        initInfo();

        imgLike.setOnClickListener(view -> {
            if (UserUtils.getUser(getApplicationContext()) != null) {
                setLike();
            } else {
                Toast.makeText(getApplicationContext(), "请先登录", Toast.LENGTH_SHORT).show();
            }
        });


    }

//    @Override
//    protected void onResume() {
//        super.onResume();
//        replaceFragment(0);
//        initInfo();
//    }

    @Override
    protected void onRestart() {
        super.onRestart();
        if (isShow == 1) {
            bottomView.setVisibility(View.GONE);
            replaceFragment(1);
            if (CollectionDetailListBottomFragment.isOpen == 1) {
                bottomLoad.setVisibility(View.VISIBLE);
                getRegistrations();
                CollectionDetailBottomFragment.checkCount = 0;
                CollectionDetailBottomFragment.setMaxCheck();
            } else {
                bottomView.setVisibility(View.VISIBLE);
                collectionFragment.setVisibility(View.VISIBLE);
            }
        }

    }

    private void getRegistrations() {

        Thread thread = new Thread(() -> {
            String jsonString = HttpUtils.get("/api/registration/get/" + id, null);
            JSONObject jsonResponse = JSONObject.parseObject(jsonString);
            if (jsonResponse.getInteger("status") == HttpURLConnection.HTTP_OK) {
                JSONArray jsonArray = jsonResponse.getJSONArray("value");
                registrations = JSONObject.parseArray(jsonArray.toJSONString(), Registration.class);

                handler.post(() -> {
                    detailLoading.setVisibility(View.GONE);
                    bottomView.setVisibility(View.VISIBLE);
                    collectionFragment.setVisibility(View.VISIBLE);
                    bottomLoad.setVisibility(View.GONE);
                    CollectionDetailBottomFragment.setCountAndPrice(registrations);
                });
            } else {
                handler.post(() -> {
                    Toast.makeText(getApplicationContext(), jsonResponse.getString("message"), Toast.LENGTH_SHORT).show();
                });
            }
        });
        thread.start();
    }


    private void initInfo() {
        detailLoading.setVisibility(View.VISIBLE);
        collectionFragment.setVisibility(View.GONE);
        bottomView.setVisibility(View.GONE);

        Thread thread = new Thread(() -> {
            String jsonString = HttpUtils.get("/api/goods/get/" + id, null);
            JSONObject jsonResponse = JSONObject.parseObject(jsonString);
            if (jsonResponse.getInteger("status") == HttpURLConnection.HTTP_OK) {
                JSONObject jsonValue = jsonResponse.getJSONObject("value");
                if (jsonValue == null) {
                    handler.post(() -> {
                        Toast.makeText(getApplicationContext(), "数据异常", Toast.LENGTH_SHORT).show();
                    });
                } else {
                    goodsDetail = JSONObject.parseObject(jsonValue.toJSONString(), Goods.class);
                    handler.post(() -> {
                        collectionName.setText(goodsDetail.getName());
                        mintage.setText("铸造量" + goodsDetail.getMintage());
                        circulation.setText("流通量" + goodsDetail.getCirculation());
                        price.setText("发售价" + goodsDetail.getPrice());

                        setGoodsImage();

                        CollectionDetailBottomFragment.setOnePrice(goodsDetail);
                        if (!fragmentManager.isDestroyed()) {
                            replaceFragment(1);
                        }
                        if (comeFrom == 0) {
                            detailLoading.setVisibility(View.GONE);
                            collectionFragment.setVisibility(View.VISIBLE);
                            bottomView.setVisibility(View.VISIBLE);
                        }
                        if (isShow == 0) {
                            bottomView.setVisibility(View.GONE);
                        }


                    });
                }

            } else {
                handler.post(() -> {
                    Toast.makeText(getApplicationContext(), jsonResponse.getString("message"), Toast.LENGTH_SHORT).show();
                });
            }
        });
        thread.start();

        if (user == null) {
            imgLike.setImageResource(R.drawable.baseline_add_circle_24);
        } else {
            getLike();
        }

        if (comeFrom != 0 && isShow == 1) {
            getRegistrations();
        }
    }

    private void getLike() {
        collectionMid.setVisibility(View.GONE);
        likeLoading.setVisibility(View.VISIBLE);

        Thread thread = new Thread(() -> {
            String jsonString = HttpUtils.get("/api/user/viewFollow/" + id, header);
            JSONObject jsonResponse = JSONObject.parseObject(jsonString);
            if (jsonResponse.getInteger("status") == HttpURLConnection.HTTP_OK) {
                handler.post(() -> {
                    collectionMid.setVisibility(View.VISIBLE);
                    likeLoading.setVisibility(View.GONE);
                    like = true;
                    imgLike.setImageResource(R.drawable.baseline_market_filter_down);
                });
            } else {
                handler.post(() -> {
                    collectionMid.setVisibility(View.VISIBLE);
                    likeLoading.setVisibility(View.GONE);
                    like = false;
                    imgLike.setImageResource(R.drawable.baseline_add_circle_24);
                });
            }
        });
        thread.start();

    }

    private void setLike() {
        collectionMid.setVisibility(View.GONE);
        likeLoading.setVisibility(View.VISIBLE);
        String pre = like ? "cancelFollow" : "addFollow";
        Thread thread = new Thread(() -> {
            String jsonString = HttpUtils.get("/api/user/" + pre + "/" + id, header);
            JSONObject jsonResponse = JSONObject.parseObject(jsonString);
            if (jsonResponse.getInteger("status") == HttpURLConnection.HTTP_OK) {
                handler.post(() -> {
                    if (like) {
                        imgLike.setImageResource(R.drawable.baseline_add_circle_24);
                    } else {
                        imgLike.setImageResource(R.drawable.baseline_market_filter_down);
                    }
                    collectionMid.setVisibility(View.VISIBLE);
                    likeLoading.setVisibility(View.GONE);
                    like = !like;
                    Toast.makeText(getApplicationContext(), jsonResponse.getString("message"), Toast.LENGTH_SHORT).show();
                });
            } else {
                handler.post(() -> {
                    Toast.makeText(getApplicationContext(), jsonResponse.getString("message"), Toast.LENGTH_SHORT).show();
                });
            }
        });
        thread.start();

    }

    private void setGoodsImage() {


        String goodsImagePath = "/data/data/" + getApplicationContext().getPackageName() + goodsDetail.getImage();
        File imageFile = new File(goodsImagePath);
        if (imageFile.exists()) {
            ConstraintLayout.LayoutParams lp = (ConstraintLayout.LayoutParams) collectionImg.getLayoutParams();
            lp.width = width;
            lp.height = width;
            collectionImg.setLayoutParams(lp);
            collectionImg.setImageBitmap(BitmapFactory.decodeFile(goodsImagePath));
        } else {
            Thread thread = new Thread(() -> {
                boolean result = HttpUtils.download(goodsDetail.getImage(), goodsImagePath);
                if (result) {
                    handler.post(() -> {
                        collectionImg.setImageBitmap(BitmapFactory.decodeFile(goodsImagePath));
                    });
                }
            });
            thread.start();
        }
    }


    private void replaceFragment(int z) {
        if (index == z) {
            return;
        }
        index = z;
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        Bundle bundle = new Bundle();
        bundle.putSerializable("goodsDetail", goodsDetail);
        if (collectionDetailFragment != null) {
            fragmentTransaction.hide(collectionDetailFragment);
        }
        if (collectionInfoFragment != null) {
            fragmentTransaction.hide(collectionInfoFragment);
        }


        if (index == 1) {
            fragmentTransaction.setCustomAnimations(R.anim.collection_detail_exit, R.anim.collection_detail_enter);


            collectionInfoFragment = new CollectionInfoFragment();
            collectionInfoFragment.setArguments(bundle);
            fragmentTransaction.replace(R.id.collection_fragment, collectionInfoFragment);
            fragmentTransaction.commit();
        }
        if (index == 0) {
            fragmentTransaction.setCustomAnimations(R.anim.collection_info_exit, R.anim.collection_info_enter);
            collectionDetailFragment = new CollectionDetailFragment();
            collectionDetailFragment.setArguments(bundle);
            fragmentTransaction.replace(R.id.collection_fragment, collectionDetailFragment);
            fragmentTransaction.commit();
        }

    }

}
